package mylibrary.server;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;

public class ServiceThread implements Runnable{

	private Socket connectedSocket = null;

	private String helloString = null;
	
	private static int count = 0;
	
	private static ReentrantLock lock = new ReentrantLock();
	
	ServiceThread(Socket socket) {
		connectedSocket = socket;
	}
	
	public void run() {
		increaseCount();
		
		int curCount = getCount();
		
		helloString = "hello, id = " + curCount + "\r\n";
		
		ExecutorService executor = Executors.newSingleThreadExecutor();
		
		Future<String> future = executor.submit(new TimeConsumingTask());
		
		DataOutputStream dos = null;
		
		try {
			
			dos = new DataOutputStream(connectedSocket.getOutputStream());
			dos.write(helloString.getBytes());
			
			dos.write("let's do something other.\r\n".getBytes());
			String result = future.get();
			dos.write(result.getBytes());
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(connectedSocket != null) {
				try {
					connectedSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			executor.shutdown();
		}
	}

	private int getCount() {
		int ret = 0;
		lock.lock();
		ret = count;
		return ret;
	}
	
	private void increaseCount() {
		lock.lock();
		++count;
	}
}
